<template>
  <div class="wrap-container">
    <div class="flex">
      <div class="detail_l">
        <div class="bg-white py-3 px-4">
          <div class="flex justify-between">
            <div class="manage_tit">
              <div class="line"></div>
              <p>场馆审核详情</p>
            </div>
            <div class="approval_btn">
              <el-button
                type="primary"
                @click="handleSubmit"
                v-hasPermi="['sys:approval:btn_submit_approval']"
                >提交审核</el-button
              >
              <template v-if="stadiumDetails.approval == 0">
                <template v-hasPermi="['sys:approval:btn_stadium_approval']">
                  <el-button type="primary" @click="handleApprove">通过</el-button>
                  <el-button type="warning" @click="handleRejects">驳回</el-button>
                </template>
              </template>
              <el-button @click="goBack">返回</el-button>
            </div>
          </div>
        </div>
        <div class="block_item">
          <div class="block_top">
            <p class="text-sm">场馆主体信息</p>
            <div
              class="edit"
              v-hasPermi="['sys:approval:btn_update']"
              @click="showEditEnterprise = true"
            >
              <img src="@/assets/images/icon/edit_icon.png" alt="" />
              <span>编辑</span>
            </div>
          </div>
          <div class="block_cont">
            <el-row>
              <el-col :span="6">
                <div>
                  <span>企业类型：</span>
                  <span>{{ enterpriseDetails.enterpriseType == 0 ? '企业' : '' }}</span>
                </div>
                <div>
                  <span>企业名称：</span>
                  <span>{{ enterpriseDetails.enterpriseName }}</span>
                </div>
                <div>
                  <span>统一社会信用代码：</span>
                  <span>{{ enterpriseDetails.businessLicenseNum }}</span>
                </div>
              </el-col>
              <el-col :span="6">
                <div>
                  <span>联系人姓名：</span>
                  <span>{{ enterpriseDetails.contactPerson }}</span>
                </div>
                <div>
                  <span>联系人身份证：</span>
                  <span>{{ enterpriseDetails.contactId }}</span>
                </div>
                <div>
                  <span>联系人电话：</span>
                  <span>{{ enterpriseDetails.contactPhone }}</span>
                </div>
              </el-col>
              <el-col :span="6">
                <div>
                  <span>开户名称：</span>
                  <span>{{ enterpriseDetails.accountName }}</span>
                </div>
                <div>
                  <span>开户银行：</span>
                  <span>{{ enterpriseDetails.accountBank }}</span>
                </div>
                <div>
                  <span>银行账号：</span>
                  <span>{{ enterpriseDetails.accountBankNumber }}</span>
                </div>
              </el-col>
              <el-col :span="6">
                <div>
                  <span>上级公司：</span>
                  <span>{{ enterpriseDetails.deptName }}</span>
                </div>
              </el-col>
            </el-row>
            <div class="flex">
              <div>
                <span class="label">工商营业执照</span>
                <div class="business_img mt-4">
                  <el-image
                    :src="enterpriseDetails.businessImg"
                    fit="cover"
                    :preview-src-list="enterpriseDetails.businessImgList"
                  ></el-image>
                </div>
              </div>
              <div class="card_img">
                <span class="label">身份证照片</span>
                <div class="flex mt-4">
                  <div v-for="(item, index) in enterpriseDetails.contactImg" :key="index">
                    <el-image
                      :src="item"
                      fit="cover"
                      :preview-src-list="enterpriseDetails.contactImg"
                    ></el-image>
                  </div>
                </div>
              </div>
            </div>
            <div class="contract_box">
              <div class="label">
                <span style="color: #808080">合作合同</span>
              </div>
              <div class="contract_cont">
                <div
                  class="flex"
                  v-for="(item, index) in enterpriseDetails.contractFile"
                  :key="index + '_contractFile'"
                >
                  <p>{{ item.name }}</p>
                  <span
                    class="align_center"
                    @click="downloadFile"
                    style="margin-left: 20px; color: #0988fb; cursor: pointer"
                    v-if="enterpriseDetails.contractFile?.length"
                    ><img src="@/assets/images/icon/download_icon.png" />下载合同</span
                  >
                </div>
                <div class="flex">
                  <div
                    v-for="(item, index) in enterpriseDetails.contractImg"
                    :key="index + 'contractImg'"
                    style="margin-right: 16px"
                  >
                    <el-image
                      :src="item.url"
                      fit="cover"
                      :preview-src-list="enterpriseDetails.contractImgList"
                    ></el-image>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="stadium_info mt-6">
            <div class="block_top">
              <p class="text-sm">场馆认证信息</p>
              <div
                class="edit"
                v-hasPermi="['sys:approval:btn_stadium_update']"
                @click="showEditStadium = true"
              >
                <img src="@/assets/images/icon/edit_icon.png" alt="" />
                <span>编辑</span>
              </div>
            </div>
            <div class="block_cont">
              <div class="flex">
                <div style="width: 527px">
                  <div class="info_item">
                    <span>门店名称：</span>
                    <span>{{ stadiumDetails.stadiumName }}</span>
                  </div>
                  <div class="info_item">
                    <span>场馆类型：</span>
                    <span>{{ stadiumDetails.stadiumTypeName }}</span>
                  </div>
                  <div class="info_item">
                    <span>营业时间：</span>
                    <span>{{ stadiumDetails.workDate }} {{ stadiumDetails.legalDate }}</span>
                  </div>
                  <div class="info_item">
                    <span>门店电话：</span>
                    <span>{{ stadiumDetails.phone }}</span>
                  </div>
                  <div class="info_item flex">
                    <span>门店地址：</span>
                    <div class="flex flex-wrap flex-1">
                      <p>{{ stadiumDetails.gdAddress }}</p>
                    </div>
                  </div>
                  <div class="info_item flex">
                    <span>退款说明：</span>
                    <div class="flex flex-wrap flex-1">
                      <p>{{ stadiumDetails.cancelRule }}</p>
                    </div>
                  </div>
                </div>
                <div class="ml-12">
                  <div class="info_item">
                    <span>场馆标签：</span>
                    <span>{{ stadiumDetails.stadiumLabel }}</span>
                  </div>
                  <div class="info_item">
                    <span>所属企业：</span>
                    <span>{{ stadiumDetails.enterpriseName }}</span>
                  </div>
                  <div class="info_item">
                    <span>默认价格：</span>
                    <span>{{ stadiumDetails.isDefaultPrice == 1 ? '是' : '否' }}</span>
                  </div>
                  <div class="info_item">
                    <span>退款时限：</span>
                    <span>{{ stadiumDetails.cancelHours }}小时</span>
                  </div>
                  <div class="info_item">
                    <span>提前核销时间：</span>
                    <span>{{ stadiumDetails.writeMinutes }}分钟</span>
                  </div>
                  <div class="flex info_item">
                    <span>场馆服务：</span>
                    <div class="flex flex-wrap flex-1">
                      <div
                        class="service_item"
                        v-for="(item, index) in serviceList"
                        :key="index + '_service'"
                      >
                        <div class="service_info">
                          <p>
                            <img :src="item.url" alt="" />
                          </p>
                          <span>{{ item.name }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="block_top">
                <p class="text-sm">图片信息</p>
              </div>
              <div>
                <div class="flex">
                  <div class="info_item">
                    <p class="text-custom-main">门店头像</p>
                    <div class="stadium_img mt-2.5">
                      <el-image
                        :src="stadiumDetails.headImg"
                        fit="cover"
                        :preview-src-list="headImgs"
                      ></el-image>
                    </div>
                  </div>
                  <div class="info_item ml-16">
                    <p class="text-custom-main">场馆平面图</p>
                    <div class="stadium_img mt-2.5">
                      <div v-for="(item, index) in stadiumPlanImgs" :key="index + '_stadiumImgs'">
                        <el-image
                          :src="item"
                          fit="cover"
                          :preview-src-list="stadiumPlanImgs"
                        ></el-image>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="info_item mt-1" style="margin-bottom: 7px">
                  <p>场馆相册</p>
                  <div class="stadium_img mt-2.5">
                    <div v-for="(item, index) in stadiumImgs" :key="index + '_stadiumImgs'">
                      <el-image
                        :src="item.imgUrl"
                        fit="cover"
                        :preview-src-list="stadiumImgList"
                      ></el-image>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="detail_r">
        <div class="order_track">
          <div class="order_top">
            <div class="manage_tit">
              <div class="line"></div>
              <p>场馆认证审批流程</p>
            </div>
          </div>
          <div class="track_list">
            <div class="track_item" v-for="item in recordList" :key="item.id">
              <p class="create_time">{{ item.approveTime }}</p>
              <div class="track_cont">
                <p v-if="item.type == null">{{ item.stepName }}</p>
                <template v-else>
                  <p>
                    {{ item.userName }}
                    <span class="text-color-808080">审核</span>
                    <span :style="{ color: item.stepColor }">{{
                      item.type == 1 ? '通过' : '驳回'
                    }}</span>
                  </p>
                  <p class="text-color-808080 text-xs mt-2px" v-if="item.type == 2">
                    说明：{{ item.stepName }}
                  </p>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <edit-enterprise
      :show="showEditEnterprise"
      :formData="enterpriseForm"
      @close="closeEditDialog"
    />
    <reject-reson
      ref="rejectResonRef"
      :stadiumId="stadiumId"
      :pageType="'stadium'"
      :rejectList="rejectList"
    ></reject-reson>
    <edit-stadium
      :show="showEditStadium"
      :stadiumId="stadiumId"
      @close="closeStadiumDialog"
      pageType="approval"
    />
    <approval-dialog ref="approvalDialogRef" @sure="goJumpPage"></approval-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { debounce } from '@/utils'
import {
  getEnterpriseData,
  approveStadium,
  rejectStadium,
  getStadiumApprovalList,
  getStadiumApprovalData,
  submitStadiumApproval,
} from '@/api/stadium/stadium'
import EditEnterprise from '@/components/Stadium/editEnterprise.vue'
import EditStadium from '@/components/Stadium/editStadium.vue'
import rejectReson from '@/components/Approval/rejectReson.vue'
import approvalDialog from '@/components/Approval/approvalDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义类型
interface EnterpriseDetails {
  enterpriseType: number
  enterpriseName: string
  businessLicenseNum: string
  businessImg: string
  businessImgList: string[]
  contactPerson: string
  contactId: string
  contactPhone: string
  contactImg: any
  accountName: string
  accountBank: string
  accountBankNumber: string
  deptName: string
  pactImg: string
  pactName: string
  contractFile: { name: string; url: string }[]
  contractImg: { name: string; url: string }[]
  contractImgList: string[]
}

interface FormData {
  id: null | string
  enterpriseType: string
  enterpriseName: string
  businessLicenseNum: string
  businessImg: string
  contactPerson: string
  contactPhone: string
  contactId: string
  contactImg: string
  accountName: string
  accountBank: string
  accountBankNumber: string
  pactImg: string
  pactName: string | undefined
  contractFile: Array<{ name: string; url: string }>
  contractImg: Array<{ name: string; url: string }>
  deptId: string | string[] | null
  dataFlag: null | string
  [key: string]: any
}

interface StadiumDetails {
  stadiumName: string
  stadiumTypeName: string
  workDate: string
  legalDate: string
  phone: string
  gdAddress: string
  cancelRule: string
  stadiumLabel: string
  enterpriseName: string
  isDefaultPrice: number
  cancelHours: number
  writeMinutes: number
  headImg: string
  siteLocation: string
  approval: number
}

interface StadiumImg {
  imgUrl: string
}

interface ServiceItem {
  name: string
  url: string
}

interface RecordItem {
  id: number
  approveTime: string
  stepName: string
  type: number
  userName: string
  stepColor: string
}

interface RejectItem {
  id: number
  name: string
}

// 使用 vue-router
const route = useRoute()
const router = useRouter()

// 响应式数据
const stadiumId = ref<number | null>(null)
const enterpriseDetails = ref<Partial<EnterpriseDetails>>({})
const stadiumDetails = ref<Partial<StadiumDetails>>({})
const stadiumImgs = ref<StadiumImg[]>([])
const serviceList = ref<ServiceItem[]>([])
const stadiumImgList = ref<string[]>([])
const showEditEnterprise = ref(false)
const headImgs = ref<string[]>([])
const recordList = ref<RecordItem[]>([])
const stadiumPlanImgs = ref<string[]>([])
const showEditStadium = ref(false)

const rejectList: RejectItem[] = [
  { id: 1, name: '营业执照过期/未年检' },
  { id: 2, name: '场馆主图含第三方品牌logo' },
  { id: 3, name: '法人身份证件模糊/信息不符' },
  { id: 4, name: '银行开户名与营业执照名称不一致' },
  { id: 5, name: '场馆名称与营业执照登记名称偏差' },
  { id: 6, name: '门店电话无法接通' },
  { id: 7, name: '其他原因' },
]
const checkList = ref<any[]>([])

// 组件引用
const rejectResonRef = ref<InstanceType<typeof rejectReson> | null>(null)
const approvalDialogRef = ref<InstanceType<typeof approvalDialog> | null>(null)

// 响应式数据
const enterpriseForm = ref<FormData>({
  id: null,
  enterpriseType: '',
  enterpriseName: '',
  businessLicenseNum: '',
  businessImg: '',
  contactPerson: '',
  contactPhone: '',
  contactId: '',
  contactImg: '',
  accountName: '',
  accountBank: '',
  accountBankNumber: '',
  pactImg: '',
  pactName: undefined,
  contractFile: [],
  contractImg: [],
  deptId: null,
  dataFlag: null,
})

// 方法定义
// 获取企业认证信息
const getEnterprise = async () => {
  const { data } = await getEnterpriseData({ stadiumId: stadiumId.value })
  enterpriseDetails.value = JSON.parse(JSON.stringify(data))
  enterpriseDetails.value.businessImgList = enterpriseDetails.value.businessImg?.split(',') || []
  enterpriseDetails.value.contactImg =
    enterpriseDetails.value.contactImg?.split(',').filter(Boolean) || []
  const pactImgArr = enterpriseDetails.value?.pactImg?.split(',').filter(Boolean) || []
  if (enterpriseDetails.value.pactName != '' && enterpriseDetails.value.pactName != null) {
    const files = pactImgArr[0]
    enterpriseDetails.value.contractFile = [
      { name: enterpriseDetails.value.pactName!, url: files! },
    ]
    enterpriseDetails.value.contractImg = pactImgArr.slice(1).map((url) => ({
      name: '已上传图片',
      url,
    }))
  } else {
    enterpriseDetails.value.contractImg = pactImgArr.map((url) => ({
      name: '已上传图片',
      url,
    }))
  }
  enterpriseDetails.value.contractImgList =
    enterpriseDetails.value.contractImg?.map((item) => item.url) || []
  for (const key in data) {
    if (enterpriseForm.value.hasOwnProperty(key)) {
      ;(enterpriseForm.value as any)[key] = (data as any)[key]
    }
  }
}

// 获取场馆信息
const getStadium = async () => {
  const { data } = await getStadiumApprovalData(stadiumId.value!)
  stadiumImgs.value = data.imgList
  serviceList.value = data.serviceList
  stadiumDetails.value = data.stadiumBaseData
  stadiumImgList.value = stadiumImgs.value.map((item: any) => item.imgUrl)
  headImgs.value = stadiumDetails.value.headImg?.split(',') || []
  stadiumPlanImgs.value = stadiumDetails.value.siteLocation?.split(',') || []
  if (stadiumDetails.value.stadiumLabel) {
    stadiumDetails.value.stadiumLabel = stadiumDetails.value.stadiumLabel.replace(',', '、')
  }
}

// 合同下载
const downloadFile = async () => {
  if (!enterpriseDetails.value.contractFile || enterpriseDetails.value.contractFile.length === 0) {
    return
  }
  const url = enterpriseDetails.value.contractFile[0]?.url // 替换成你要下载的文件的URL
  const fileName = enterpriseDetails.value.contractFile[0]?.name // 自定义文件名
  if (url && fileName) {
    const response = await fetch(url)
    const blob = await response.blob()
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

// 关闭编辑弹窗
const closeEditDialog = (val?: number) => {
  showEditEnterprise.value = false
  if (val == 1) {
    getEnterprise()
  }
}

// 通过审批
const handleApprove = () => {
  ElMessageBox.confirm(`是否确认通过该场馆的审批？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return approveStadium(stadiumId.value!).then(() => {
        ElMessage.success('操作成功')
        router.go(-1)
      })
    })
    .catch(() => {})
}

// 驳回审批
const handleRejects = () => {
  if (rejectResonRef.value) {
    rejectResonRef.value.showRejectModal = true
    checkList.value = []
  }
}

// 选择驳回原因
const changeReject = () => {
  // 这个方法在模板中没有被使用，但保留在代码中以维持功能完整性
}

// 获取审批流程
const getApprovalList = async () => {
  const { data } = await getStadiumApprovalList(stadiumId.value!)
  recordList.value = data
}

// 返回
const goBack = () => {
  router.go(-1)
}

// 关闭修改场馆信息弹窗
const closeStadiumDialog = (val?: number) => {
  showEditStadium.value = false
  getStadium()
}

// 提交审核
const handleSubmit = debounce(
  async () => {
    await submitStadiumApproval({ stadiumId: stadiumId.value })
    if (approvalDialogRef.value) {
      approvalDialogRef.value.approvalVisible = true
    }
  },
  1000,
  // {
  //   // leading: true,
  //   // trailing: false,
  // },
)

// 提交审核跳转页面
const goJumpPage = () => {
  router.go(-1)
}

// 生命周期
onMounted(() => {
  stadiumId.value = Number(route.query.id as string) || null
  getEnterprise()
  getStadium()
  getApprovalList()
})
</script>

<style lang="scss" scoped>
.wrap-container {
  .approval_btn {
    display: flex;
    justify-content: flex-end;
    .el-button {
      width: 80px;
      height: 32px;
      line-height: 32px;
      border-radius: 6px;
      padding: 0;
      &.el-button--primary {
        background: #0988fb;
        border-color: #0988fb;
      }
      &.el-button--warning {
        background: #ff8d1a;
        border-color: #ff8d1a;
      }
      &.el-button--default {
        border-color: #a6a6a6;
        color: #383838;
        background: #fff;
      }
      & + .el-button {
        margin-left: 12px;
      }
    }
  }
  .detail_l {
    flex: 1;
  }
  .block_item {
    background: #fff;
    padding: 15px;
    height: calc(100vh - 143px);
    overflow-y: auto;
    &:not(:first-child) {
      margin-top: 15px;
    }
    .block_top {
      padding-bottom: 9px;
      border-bottom: 1px solid #e5e5e5;
      margin-bottom: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .edit {
        font-size: 14px;
        color: #2a82e4;
        display: flex;
        align-items: center;
        cursor: pointer;
        img {
          width: 15px;
          height: 15px;
          margin-right: 7px;
        }
      }
    }
    .block_cont {
      .business_img {
        .el-image {
          width: 150px;
          height: 110px;
          border-radius: 7px;
        }
      }
      .card_img {
        margin-left: 166px;
        .el-image {
          width: 173px;
          height: 110px;
          margin-right: 16px;
          border-radius: 7px;
        }
      }
      .label {
        font-size: 14px;
        color: #808080;
        margin-right: 24px;
      }
      .contract_box {
        margin-top: 21px;
        .contract_cont {
          flex: 1;
          font-size: 14px;
          .el-image {
            width: 95px;
            height: 110px;
            margin-top: 16px;
            border-radius: 4px;
          }
        }
      }
    }
    :deep(.el-row) {
      .el-col {
        div {
          margin-bottom: 16px;
          font-size: 14px;
          span {
            &:first-child {
              color: #808080;
            }
            &:last-child {
              color: #292929;
              margin-left: 10px;
            }
          }
        }
      }
    }
    .approval_btn {
      display: flex;
      justify-content: flex-end;
      .el-button {
        width: 79px;
      }
    }
  }
  .stadium_info {
    .info_item {
      margin-bottom: 18px;
      font-size: 14px;
      color: #383838;
      span {
        &:first-child {
          color: #808080;
        }
      }
      .stadium_img {
        display: flex;
        flex-wrap: wrap;
        .el-image {
          width: 110px;
          height: 110px;
          margin-right: 10px;
        }
      }
    }
    .service_item {
      display: inline-block;
      margin-bottom: 16px;
      margin-right: 30px;
      .service_info {
        display: flex;
        align-items: center;
        p {
          width: 20px;
          height: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 8px;
          img {
            width: 100%;
          }
        }
        span {
          font-size: 14px;
          color: #808080;
          display: block;
          line-height: 21px;
        }
      }
    }
  }
  .detail_r {
    margin-left: 15px;
    width: 367px;
    .order_track {
      background: #fff;
      padding: 10px 16px;
      height: calc(100vh - 80px);
      overflow-y: auto;
      .order_top {
        margin-bottom: 0;
      }
      .track_list {
        padding: 11px 12px 0;
        .track_item {
          margin-bottom: 15px;
          .create_time {
            color: #808080;
            line-height: 18px;
            font-size: 12px;
            margin-bottom: 2px;
          }
          .track_cont {
            font-size: 14px;
            line-height: 21px;
            margin: 2px 0;
            span {
              margin: 0 8px;
            }
            .green {
              color: #00baad;
            }
            .red {
              color: #d43030;
            }
            .primary {
              color: #2a82e4;
            }
          }
        }
      }
    }
  }
}
</style>
